﻿using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.SaleOrderAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands;

public class CreateSaleOrderCommand : SaleOrderEditRequestDto, IRequest<Result<SaleOrderInfoResponseDto>>
{
}


public class CreateSaleOrderCommandHandler : IRequestHandler<CreateSaleOrderCommand, Result<SaleOrderInfoResponseDto>>
{
    private readonly ISaleOrderRepository _saleOrderRepository;
    private readonly IMapper _mapper;

    public CreateSaleOrderCommandHandler(ISaleOrderRepository saleOrderRepository,
        IMapper mapper)
    {
        this._saleOrderRepository = saleOrderRepository;
        this._mapper = mapper;
    }

    public async Task<Result<SaleOrderInfoResponseDto>> Handle(CreateSaleOrderCommand request, CancellationToken cancellationToken)
    {
        var saleOrder = new SaleOrder(request.SaleOrderCode, request.SaleOrderName, request.Description,
            request.CustomerId, request.CustomerOrderCode, request.ContractOrderCode, request.DeliveryTime, request.SaleOrderType);
        _saleOrderRepository.Add(saleOrder);

        if (request.Items.Count > 0)
        {
            foreach (var item in request.Items)
            {
                saleOrder.AddItem(item.MaterialId, item.ExcludingTaxPrice, item.IncludingTaxPrice, item.Tax,
                    item.DeliveryTime, item.Quantity);
            }
        }

        await _saleOrderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return await Result<SaleOrderInfoResponseDto>.SuccessAsync(_mapper.Map<SaleOrderInfoResponseDto>(saleOrder));
    }
}